# 创建新的资源图片页面
<template>
  <div class="resource-container">
    <a-tabs v-model:activeKey="activeTab">
      <a-tab-pane key="unsplash" tab="Unsplash图片">
        <div class="tab-content">
          <UnsplashPic v-if="activeTab === 'unsplash'" />
        </div>
      </a-tab-pane>
      <a-tab-pane key="url" tab="URL图片">
        <div class="tab-content">
          <div class="url-pic-container">
            <a-spin :spinning="loading" tip="加载中..." size="large">
              <!-- 搜索区域 -->
              <div class="search-fixed">
                <a-card class="search-card" :bordered="false">
                  <a-space>
                    <a-input-search
                      v-model:value="searchText"
                      placeholder="搜索图片关键词..."
                      style="width: 300px"
                      @search="handleSearch"
                      size="large"
                      allow-clear
                    >
                      <template #addonAfter>
                        <a-input-number
                          v-model:value="count"
                          :min="1"
                          :max="30"
                          style="width: 80px"
                          placeholder="数量"
                        />
                      </template>
                    </a-input-search>
                    <a-button :type="isAllSelected ? 'primary' : 'default'" @click="selectAll">
                      <template #icon><SelectOutlined /></template>
                      {{ isAllSelected ? '取消全选' : '全选本页' }}
                    </a-button>
                    <a-button
                      type="primary"
                      :disabled="selectedImages.length === 0"
                      @click="handleDownloadAndUpload"
                    >
                      <template #icon><UploadOutlined /></template>
                      下载并上传 ({{ selectedImages.length }})
                    </a-button>
                    <a-button :loading="refreshing" @click="refreshCurrentPage">
                      <template #icon><SyncOutlined /></template>
                    </a-button>
                  </a-space>
                </a-card>
              </div>

              <!-- 图片内容区域 -->
              <div class="content-area">
                <a-card class="image-card" :bordered="false">
                  <!-- 图片网格 -->
                  <div class="image-grid">
                    <div v-for="image in images" :key="image.id" class="image-item">
                      <div class="image-card">
                        <div class="select-overlay" @click.stop="toggleSelect(image)">
                          <a-checkbox :checked="isSelected(image)" />
                        </div>
                        <div class="image-wrapper">
                          <img
                            :src="image.url"
                            :alt="image.description || '暂无描述'"
                            class="image"
                            @error="handleImageError"
                          />
                        </div>
                      </div>
                    </div>
                  </div>
                </a-card>
              </div>
            </a-spin>
          </div>
        </div>
      </a-tab-pane>
    </a-tabs>
  </div>
</template>

<script lang="ts" setup>
  import { ref, computed } from 'vue'
  import { message } from 'ant-design-vue'
  import { SelectOutlined, UploadOutlined, SyncOutlined } from '@ant-design/icons-vue'
  import { useRouter } from 'vue-router'
  import UnsplashPic from './UnsplashPic.vue'
  import axios from 'axios'

  // 类型定义
  interface UrlImage {
    id: string
    url: string
    description: string
  }

  // 状态定义
  const activeTab = ref('unsplash')
  const loading = ref(false)
  const refreshing = ref(false)
  const searchText = ref('')
  const count = ref(20)
  const images = ref<UrlImage[]>([])
  const selectedImages = ref<UrlImage[]>([])

  const router = useRouter()

  // 图片错误处理
  const handleImageError = (e: Event) => {
    const img = e.target as HTMLImageElement
    img.src = '/src/assets/default_image.png'
  }

  // 获取图片列表
  const fetchImages = async () => {
    if (!searchText.value) {
      message.warning('请输入搜索关键词')
      return
    }

    loading.value = true
    try {
      // 构建 URL
      const searchQuery = encodeURIComponent(searchText.value)
      const url = `https://cn.bing.com/images/async?q=${searchQuery}&mmasync=1`

      // 发起请求
      const response = await axios.get(url)
      const parser = new DOMParser()
      const doc = parser.parseFromString(response.data, 'text/html')

      // 解析图片
      const div = doc.querySelector('.dgControl')
      if (!div) {
        throw new Error('获取元素失败')
      }

      const imgElements = div.querySelectorAll('img.mimg')
      const newImages: UrlImage[] = []

      imgElements.forEach((img, index) => {
        let fileUrl = img.getAttribute('src') || ''
        if (!fileUrl) return

        // 处理 URL
        const questionMarkIndex = fileUrl.indexOf('?')
        if (questionMarkIndex > -1) {
          fileUrl = fileUrl.substring(0, questionMarkIndex)
        }

        newImages.push({
          id: `url-${index}-${Date.now()}`,
          url: fileUrl,
          description: searchText.value,
        })
      })

      // 更新图片列表
      images.value = newImages.slice(0, count.value)
    } catch (error: unknown) {
      console.error('获取图片失败：', error)
      const errorMessage = error instanceof Error ? error.message : '未知错误'
      message.error('获取图片失败：' + errorMessage)
    } finally {
      loading.value = false
    }
  }

  // 刷新当前页
  const refreshCurrentPage = async () => {
    refreshing.value = true
    try {
      await fetchImages()
    } finally {
      refreshing.value = false
    }
  }

  // 搜索处理
  const handleSearch = () => {
    if (count.value > 30) {
      message.warning('最多获取30张图片')
      count.value = 30
      return
    }
    fetchImages()
  }

  // 切换选择状态
  const toggleSelect = (image: UrlImage) => {
    const index = selectedImages.value.findIndex(img => img.id === image.id)
    if (index === -1) {
      selectedImages.value.push(image)
    } else {
      selectedImages.value.splice(index, 1)
    }
  }

  // 检查是否被选中
  const isSelected = (image: UrlImage) => {
    return selectedImages.value.some(img => img.id === image.id)
  }

  // 全选功能
  const selectAll = () => {
    if (images.value.every(img => isSelected(img))) {
      selectedImages.value = []
    } else {
      selectedImages.value = [...images.value]
    }
  }

  // 检查是否全选
  const isAllSelected = computed(() => {
    return images.value.length > 0 && images.value.every(img => isSelected(img))
  })

  // 下载并上传处理
  const handleDownloadAndUpload = async () => {
    if (selectedImages.value.length === 0) {
      message.warning('请先选择图片')
      return
    }

    try {
      // 存储选中的图片信息到 sessionStorage
      const imageInfos = selectedImages.value.map(image => ({
        id: image.id,
        url: image.url,
        description: image.description || '',
        authorName: '',
        tags: [],
      }))

      sessionStorage.setItem('urlPendingImages', JSON.stringify(imageInfos))

      message.success(`已选择 ${selectedImages.value.length} 张图片`)
      router.push('/user/createPicture?from=url&total=' + selectedImages.value.length)
    } catch (error) {
      message.error('处理图片失败，请重试')
      console.error('处理图片失败:', error)
    }
  }
</script>

<style scoped>
  .resource-container {
    padding: 4px;
    background: var(--theme-background);
    min-height: calc(100vh - 70px);
    transition: all 0.3s ease;
  }

  .tab-content {
    height: calc(100vh - 120px);
    overflow: auto;
  }

  .url-pic-container {
    position: relative;
    min-height: calc(100vh - 120px);
  }

  .search-fixed {
    position: sticky;
    top: 0;
    z-index: 100;
    background: var(--theme-background);
    padding: 4px 4px 0;
    transition: all 0.3s ease;
  }

  .search-card {
    background: var(--theme-surface);
    border-radius: 8px;
    margin-bottom: 0;
    border: 1px solid var(--theme-border);
    box-shadow: 0 2px 8px var(--theme-shadow);
    transition: all 0.3s ease;
  }

  .content-area {
    margin-top: 80px;
  }

  .image-grid {
    display: grid;
    grid-template-columns: repeat(6, 1fr);
    gap: 16px;
    padding: 0;
    margin: 0;
    background: transparent;
  }

  .image-item {
    position: relative;
    aspect-ratio: 1;
  }

  .image-card {
    cursor: pointer;
    border-radius: 8px;
    overflow: hidden;
    background: var(--theme-surface);
    box-shadow: 0 2px 8px var(--theme-shadow);
    border: 1px solid var(--theme-border);
    transition: all 0.3s ease;
  }

  .image-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 16px var(--theme-shadow);
    border-color: var(--theme-primary);
  }

  .image-wrapper {
    position: relative;
    width: 100%;
    height: 200px;
    background: var(--theme-background);
    overflow: hidden;
    transition: all 0.3s ease;
  }

  .image {
    width: 100%;
    height: 100%;
    object-fit: cover;
    transition: transform 0.3s ease;
  }

  .select-overlay {
    position: absolute;
    top: 8px;
    left: 8px;
    z-index: 2;
    background: rgba(255, 255, 255, 0.9);
    border-radius: 4px;
    padding: 4px;
    cursor: pointer;
    transition: all 0.3s ease;
    border: 1px solid var(--theme-border);
  }

  /* 深色主题下的选择覆盖层 */
  [data-theme="dark"] .select-overlay {
    background: rgba(0, 0, 0, 0.8);
    border-color: var(--theme-border);
  }

  /* 深色主题下的选择覆盖层 */
  [data-theme="dark"] .select-overlay:hover {
    background: rgba(0, 0, 0, 0.9);
    border-color: var(--theme-primary);
  }

  /* 浅色主题下的选择覆盖层 */
  [data-theme="light"] .select-overlay:hover {
    background: rgba(255, 255, 255, 1);
    border-color: var(--theme-primary);
    box-shadow: 0 2px 8px var(--theme-shadow);
  }

  :deep(.ant-card-body) {
    padding: 16px;
    background: var(--theme-surface);
    transition: all 0.3s ease;
  }

  :deep(.ant-tabs-nav) {
    margin: 0;
    padding: 0 16px;
    background: var(--theme-surface);
    border-bottom: 1px solid var(--theme-border);
    transition: all 0.3s ease;
  }

  :deep(.ant-tabs-tab) {
    color: var(--theme-text);
    transition: all 0.3s ease;
  }

  :deep(.ant-tabs-tab:hover) {
    color: var(--theme-primary);
  }

  :deep(.ant-tabs-tab-active) {
    color: var(--theme-primary);
  }

  :deep(.ant-tabs-ink-bar) {
    background: var(--theme-primary);
    transition: all 0.3s ease;
  }

  :deep(.ant-tabs-content-holder) {
    overflow: auto;
    background: var(--theme-background);
    transition: all 0.3s ease;
  }

  :deep(.ant-tabs-content) {
    height: 100%;
  }

  /* 输入框主题适配 */
  :deep(.ant-input-search .ant-input) {
    background: var(--theme-surface);
    border-color: var(--theme-border);
    color: var(--theme-text);
    transition: all 0.3s ease;
  }

  :deep(.ant-input-search .ant-input:hover) {
    border-color: var(--theme-primary);
  }

  :deep(.ant-input-search .ant-input:focus) {
    border-color: var(--theme-primary);
    box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
  }

  :deep(.ant-input-search .ant-input::placeholder) {
    color: var(--theme-textSecondary);
  }

  :deep(.ant-input-search .ant-input-group-addon) {
    background: var(--theme-surface);
    border-color: var(--theme-border);
    color: var(--theme-text);
    transition: all 0.3s ease;
  }

  /* 数字输入框主题适配 */
  :deep(.ant-input-number) {
    background: var(--theme-surface);
    border-color: var(--theme-border);
    color: var(--theme-text);
    transition: all 0.3s ease;
  }

  :deep(.ant-input-number:hover) {
    border-color: var(--theme-primary);
  }

  :deep(.ant-input-number:focus) {
    border-color: var(--theme-primary);
    box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
  }

  :deep(.ant-input-number::placeholder) {
    color: var(--theme-textSecondary);
  }

  /* 按钮主题适配 */
  :deep(.ant-btn) {
    transition: all 0.3s ease;
  }

  :deep(.ant-btn-default) {
    background: var(--theme-surface);
    border-color: var(--theme-border);
    color: var(--theme-text);
  }

  :deep(.ant-btn-default:hover) {
    border-color: var(--theme-primary);
    color: var(--theme-primary);
  }

  :deep(.ant-btn-primary) {
    background: var(--theme-primary);
    border-color: var(--theme-primary);
    color: var(--theme-surface);
  }

  :deep(.ant-btn-primary:hover) {
    background: var(--theme-secondary);
    border-color: var(--theme-secondary);
    color: var(--theme-surface);
  }

  /* 复选框主题适配 */
  :deep(.ant-checkbox) {
    transition: all 0.3s ease;
  }

  :deep(.ant-checkbox .ant-checkbox-inner) {
    background: var(--theme-surface);
    border-color: var(--theme-border);
    transition: all 0.3s ease;
  }

  :deep(.ant-checkbox:hover .ant-checkbox-inner) {
    border-color: var(--theme-primary);
  }

  :deep(.ant-checkbox-checked .ant-checkbox-inner) {
    background: var(--theme-primary);
    border-color: var(--theme-primary);
  }

  /* 加载状态主题适配 */
  :deep(.ant-spin) {
    color: var(--theme-primary);
  }

  :deep(.ant-spin-dot-item) {
    background-color: var(--theme-primary);
  }

  /* 响应式设计 */
  @media (max-width: 1200px) {
    .image-grid {
      grid-template-columns: repeat(5, 1fr);
    }
  }

  @media (max-width: 992px) {
    .image-grid {
      grid-template-columns: repeat(4, 1fr);
    }
  }

  @media (max-width: 768px) {
    .image-grid {
      grid-template-columns: repeat(3, 1fr);
    }
    
    .search-fixed {
      padding: 8px;
    }
    
    .search-card {
      margin: 0 8px;
    }
  }

  @media (max-width: 576px) {
    .image-grid {
      grid-template-columns: repeat(2, 1fr);
      gap: 12px;
    }
    
    .image-wrapper {
      height: 150px;
    }
  }
</style>
